﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

//update 和 fixedupdate的比较
public class UpdateVSfixedupdate : MonoBehaviour
{
    [SerializeField]
    private InputField m_TimeLimitIF;
    [SerializeField]
    private InputField m_FrameLimitIF;
    [SerializeField]
    private Toggle m_UpdateToggle;
    [SerializeField]
    private Text m_ResultLabel;
    [SerializeField]
    private Button m_StartBtn;

    private Rigidbody m_Rb;
    private bool m_CanRun;
    private float m_TotalCount;
    private float m_TimeRemain;

    private void Awake()
    {
        m_Rb = GetComponent<Rigidbody>();
        m_StartBtn.onClick.AddListener(OnStartBtnClick);
        m_TimeLimitIF.text = "5";
        m_FrameLimitIF.text = "60";
    }

    private void Update()
    {
        if (!m_UpdateToggle.isOn) return;
        Run();
    }

    private void FixedUpdate()
    {
        if (m_UpdateToggle.isOn) return;
        Run();
    }

    private void Run()
    {
        if (!m_CanRun) return;

        m_TimeRemain -= Time.deltaTime;
        m_TotalCount++;
        if (m_TimeRemain < 0 )
        {
            m_StartBtn.gameObject.SetActive(true);
            m_CanRun = false;
            m_ResultLabel.text =
                $"帧率限制：{m_FrameLimitIF.text}\n" +
                $"总耗时：{m_TimeLimitIF.text}s\n" +
                $"调用次数：{m_TotalCount}";
        }
        else
        {
            m_ResultLabel.text = $"剩余时间:{m_TimeRemain}s";
        }
    }

    private void OnStartBtnClick()
    {
        Application.targetFrameRate = int.Parse(m_FrameLimitIF.text);
        m_TimeRemain = float.Parse(m_TimeLimitIF.text);
        m_TotalCount = 0;
        m_CanRun = true;
        m_StartBtn.gameObject.SetActive(false);
    }
}
